package com.hello.sky.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hello.sky.constant.MessageConstant;
import com.hello.sky.mapper.OrdersMapper;
import com.hello.sky.model.entity.Orders;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
//@Component
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 通过定时任务每分钟检查一次是否存在支付超时订单（下单后超过15分钟仍未支付则判定为支付超时订单），如果存在则修改订单状态为“已取消”
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void checkTimedOutOrder(){
        log.info("开始检查是否存在超时订单");
        //查询所有未支付的订单
        List<Orders> ordersList = ordersMapper.selectList(new LambdaQueryWrapper<Orders>().eq(Orders::getStatus, Orders.PENDING_PAYMENT));
        //过滤出超出15分钟的订单
        List<Orders> cancelList = ordersList.stream().filter(orders -> {
            LocalDateTime openTime = orders.getOrderTime(); //下单时间
            LocalDateTime now = LocalDateTime.now();    //当前时间
            Duration abs = Duration.between(openTime, now).abs();
            return abs.toMinutes() >= 15; //相差是都超过15分钟
        }).toList();
        int size = cancelList.size();
        log.info("超时订单数：{}", size);
        if (!(size > 0)) return;
        //填充取消信息
        cancelList.forEach(cancel -> {
            cancel.setStatus(Orders.CANCELLED);
            cancel.setCancelTime(LocalDateTime.now());
            cancel.setCancelReason(MessageConstant.ORDER_PAY_TIME_OUT);
        });
        //更新数据库
        ordersMapper.updateBatch(cancelList);
    }

    /**
     * 通过定时任务每天凌晨1点检查一次是否存在“派送中”的订单，如果存在则修改订单状态为“已完成”
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void checkDeliveryOrder(){
        log.info(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " 开始检查是否存在“派送中”的订单");
        List<Orders> ordersList = ordersMapper.TimeOutDailyScan(Orders.DELIVERY_IN_PROGRESS);
        ordersList.forEach(orders -> {
            //修改订单状态、送达时间
            orders.setStatus(Orders.COMPLETED);
            orders.setDeliveryTime(LocalDateTime.now());
        });

        ordersMapper.updateBatch(ordersList);
    }
}
